/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.winexpress.product;

import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.winexpress.util.Log;
import com.winexpress.util.SessionAttributes;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceRef;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Sihua
 */
@WebServlet(name = "WineAddEditHandler", urlPatterns = {"/wineAddEditHandler/*"})
public class WineAddEditHandler extends HttpServlet {

    @WebServiceRef(wsdlLocation = "WEB-INF/wsdl/localhost_8080/WineXpress-war/ProductManagementWS.wsdl")
    private ProductManagementWS_Service service;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try {
            RequestDispatcher dispatcher;
            ServletContext servletContext = getServletContext();
            String page = request.getPathInfo().substring(1);
            System.out.println(page);

            HttpSession session = request.getSession();

            ProductManagementWS port = service.getProductManagementWSPort();

            //add wine
            if ("manageWines".equals(page)) {
                String path = null;
                String name = null;
                String description = null;
                String categoryID = null;
                String producer = null;
                String country = null;
                String region = null;
                String varietal = null;
                String vintage = null;
                String stock = null;
                String volume = null;
                String price = null;
                String cost = null;
                String discount = null;
                String isActive = "false";
                List<FileItem> items = null;

                try {
                    items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                } catch (FileUploadException e) {
                    throw new ServletException("Cannot parse multipart request.", e);
                }

                for (FileItem item : items) {
                    if (item.isFormField()) {

                        if (item.getFieldName().equals("name")) {
                            name = item.getString();
                        }
                        if (item.getFieldName().equals("description")) {
                            description = item.getString();
                        }
                        if (item.getFieldName().equals("category")) {
                            categoryID = item.getString();
                        }
                        if (item.getFieldName().equals("producer")) {
                            producer = item.getString();
                        }
                        if (item.getFieldName().equals("country")) {
                            country = item.getString();
                        }
                        if (item.getFieldName().equals("region")) {
                            region = item.getString();
                        }
                        if (item.getFieldName().equals("varietal")) {
                            varietal = item.getString();
                        }
                        if (item.getFieldName().equals("vintage")) {
                            vintage = item.getString();
                        }
                        if (item.getFieldName().equals("stock")) {
                            stock = item.getString();
                        }
                        if (item.getFieldName().equals("volume")) {
                            volume = item.getString();
                        }
                        if (item.getFieldName().equals("price")) {
                            price = item.getString();
                        }
                        if (item.getFieldName().equals("cost")) {
                            cost = item.getString();
                        }
                        if (item.getFieldName().equals("discount")) {
                            discount = item.getString();
                        }
                        if (item.getFieldName().equals("isActive")) {
                            isActive = item.getString();
                        }
                    } else {
                        // Process uploaded fields here.
                        Random rand = new Random();
                        String filename = Long.toString(rand.nextLong());

                        path = getServletConfig().getServletContext().getRealPath("/resources/tmp/");
                        File file = new File(path + File.separator + filename); // Define destination file.

                        try {
                            item.write(file); // Write to destination file.pat
                        } catch (Exception ex) {

                        }
                        path = file.getAbsolutePath();
                    }
                }

                if (isActive != null) {
                    isActive = "true";
                }

                Wine newWine = new Wine();
                newWine.setName(name);
                newWine.setDescription(description);
                newWine.setProducer(producer);
                newWine.setCountry(country);
                newWine.setRegion(region);
                newWine.setVarietal(varietal);
                newWine.setVintage(vintage);
                newWine.setStock(new Integer(stock).intValue());
                newWine.setVolume(new Integer(volume).intValue());
                Double p = new Double(price);
                newWine.setPrice(p.doubleValue());
                newWine.setCost(new Double(cost).doubleValue());
                Double d = new Double(discount);
                newWine.setDiscount(d.doubleValue());
                if (isActive.equals("true")) {
                    newWine.setIsActive(true);
                } else {
                    newWine.setIsActive(false);
                }
                Long addedWineID = port.addWine(newWine);

                newWine = port.getWine(addedWineID);
                String url = UploadImage(path, addedWineID.toString());
                newWine.setImageUrl(url);
                port.editWine(newWine);

                Wine addedWine = port.getWine(addedWineID.longValue());
                Category c = port.getCategory(new Long(categoryID).longValue());
                c.getWine().add(addedWine);
                port.editCategory(c);

                request.setAttribute("isAdd", true);
                
                Log.info("adminID = " + SessionAttributes.USER_ID  + "add wine "+addedWineID);
                ;
            } //edit wine
            else if ("editWines".equals(page)) {
                String path = null;
                String wineID = null;
                String name = null;
                String description = null;
                String oldCategoryID = null;
                String categoryID = null;
                String producer = null;
                String country = null;
                String region = null;
                String varietal = null;
                String vintage = null;
                String stock = null;
                String volume = null;
                String price = null;
                String cost = null;
                String discount = null;

                List<FileItem> items = null;

                try {
                    items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                } catch (FileUploadException e) {
                    throw new ServletException("Cannot parse multipart request.", e);
                }
                for (FileItem item : items) {
                    if (item.isFormField()) {

                        if (item.getFieldName().equals("wineID")) {
                            wineID = item.getString();
                        }
                        if (item.getFieldName().equals("oldCategoryID")) {
                            oldCategoryID = item.getString();
                        }
                        if (item.getFieldName().equals("name")) {
                            name = item.getString();
                        }
                        if (item.getFieldName().equals("description")) {
                            description = item.getString();
                        }
                        if (item.getFieldName().equals("category")) {
                            categoryID = item.getString();
                        }
                        if (item.getFieldName().equals("producer")) {
                            producer = item.getString();
                        }
                        if (item.getFieldName().equals("country")) {
                            country = item.getString();
                        }
                        if (item.getFieldName().equals("region")) {
                            region = item.getString();
                        }
                        if (item.getFieldName().equals("varietal")) {
                            varietal = item.getString();
                        }
                        if (item.getFieldName().equals("vintage")) {
                            vintage = item.getString();
                        }
                        if (item.getFieldName().equals("stock")) {
                            stock = item.getString();
                        }
                        if (item.getFieldName().equals("volume")) {
                            volume = item.getString();
                        }
                        if (item.getFieldName().equals("price")) {
                            price = item.getString();
                        }
                        if (item.getFieldName().equals("cost")) {
                            cost = item.getString();
                        }
                        if (item.getFieldName().equals("discount")) {
                            discount = item.getString();
                        }
                    } else {
                        Random rand = new Random();
                        String filename = Long.toString(rand.nextLong());

                        path = getServletConfig().getServletContext().getRealPath("/resources/tmp/");
                        File file = new File(path + File.separator + filename);

                        try {
                            item.write(file);
                        } catch (Exception ex) {
                        }

                        if (file.length() != 0) {
                            path = file.getAbsolutePath();
                            System.out.println(file.getAbsolutePath());
                        } else {
                            path = "oldPath";
                            file.delete();
                        }
                    }
                }
                long id = new Long(wineID).longValue();
                Wine editedWine = port.getWine(id);

                long newID = new Long(categoryID).longValue();
                long oldID = new Long(oldCategoryID).longValue();

                if (newID != oldID) {
                    Category oldCategory = port.getCategory(oldID);
                    List<Wine> list = oldCategory.getWine();

                    Iterator it = list.iterator();
                    while (it.hasNext()) {
                        Wine w = (Wine) it.next();
                        if (w.getId().longValue() == id) {
                            it.remove();
                        }
                    }

                    port.editCategory(oldCategory);
                }

                editedWine.setName(name);
                editedWine.setDescription(description);
                editedWine.setProducer(producer);
                editedWine.setCountry(country);
                editedWine.setRegion(region);
                editedWine.setVarietal(varietal);
                editedWine.setVintage(vintage);
                editedWine.setStock(new Integer(stock).intValue());
                editedWine.setVolume(new Integer(volume).intValue());
                Double p = new Double(price);
                editedWine.setPrice(p.doubleValue());
                editedWine.setCost(new Double(cost).doubleValue());
                Double d = new Double(discount);
                editedWine.setDiscount(d.doubleValue());

                if (!path.equals("oldPath")) {
                    String url = UploadImage(path, new Long(id).toString());
                    editedWine.setImageUrl(url);
                }

                Boolean isEdit = port.editWine(editedWine);
                editedWine = port.getWine(id);

                if (newID != oldID) {
                    Category newCategory = port.getCategory(newID);
                    newCategory.getWine().add(editedWine);
                    port.editCategory(newCategory);
                }

                //request.setAttribute("isEdit",true);
                response.sendRedirect("/WineXpressClient/manageWines.jsp");
                request.setAttribute("isEdit", isEdit);
                
                Log.info("adminID = " + SessionAttributes.USER_ID  + "edit wine "+editedWine.getId());
            }

            List<Wine> list = port.listWines();
            session.setAttribute("winesList", list);

            session.setAttribute("wineCategoryList", this.getCategoryList(list));

            dispatcher = servletContext.getNamedDispatcher(page);

            if (dispatcher == null) {
                dispatcher = servletContext.getNamedDispatcher("Error");
            }

            dispatcher.forward(request, response);
        } catch (Exception ex) {
            log("Exception in ProductManagement servlet");
            log(ex.toString());
        }
    }

    private List<Category> getCategoryList(List<Wine> list) {
        ProductManagementWS port = service.getProductManagementWSPort();
        List<Category> categoryList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Wine w = (Wine) list.get(i);
            Category c = port.findCategory(w.getId().toString());
            categoryList.add(c);
        }
        return categoryList;
    }

    public String UploadImage(String path, String name) {
        String url = null;

        try {
            AmazonS3 s3 = new AmazonS3Client((new PropertiesCredentials(WineAddEditHandler.class.getResourceAsStream("AwsCredentials.properties"))));

            String bucketName = "winexpress-grp6";
            String key = name;
            File myfile = new File(path);

            PutObjectRequest putObj = new PutObjectRequest(bucketName, key, myfile);
            putObj.setCannedAcl(CannedAccessControlList.PublicRead);
            s3.putObject(putObj);
            url = "https://s3-us-west-2.amazonaws.com/winexpress-grp6/" + name;
            myfile.delete();
        } catch (IOException ex) {
            Logger.getLogger(WineAddEditHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return url;
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
